<?php

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Wire\AMQPTable;

require __DIR__ . '/../../vendor/autoload.php';

$config = require(__DIR__ . '/../config.php');
$connection = new AMQPStreamConnection(
    $config['host'],
    $config['port'],
    $config['user'],
    $config['password'],
    $config['vhost']
);

$channel = $connection->channel();

const DELAY_EXCHANGE = 'delay_exchange';
const NORMAL_EXCHANE = 'normal_exchange';
const QUEUE_A = "queue_10s";
const QUEUE_B = "queue_40s";
const QUEUE_QC = "queue_qc";
const DELAY_QUEUE = 'queue_delay';

// 正常交换机
$channel->exchange_declare(NORMAL_EXCHANE, 'direct');

// 队列A
$channel->queue_declare(QUEUE_A, false, false, false, false, false, new AMQPTable([
    'x-dead-letter-exchange' => DELAY_EXCHANGE, // 死信交换机
    'x-dead-letter-routing-key' => 'rk_delay', // 死信路由key
    'x-message-ttl' => 10*1000 , // 10秒过期
]));

// 队列B
$channel->queue_declare(QUEUE_B, false, false, false, false, false, new AMQPTable([
    'x-dead-letter-exchange' => DELAY_EXCHANGE, // 死信交换机
    'x-dead-letter-routing-key' => 'rk_delay', // 死信路由key
    'x-message-ttl' => 40*1000 , // 10秒过期
]));

// 队列C
$channel->queue_declare(QUEUE_QC, false, false, false, false, false, new AMQPTable([
    'x-dead-letter-exchange' => DELAY_EXCHANGE, // 死信交换机
    'x-dead-letter-routing-key' => 'rk_delay', // 死信路由key
]));

$channel->queue_bind(QUEUE_A, NORMAL_EXCHANE, 'rk_a');
$channel->queue_bind(QUEUE_B, NORMAL_EXCHANE, 'rk_b');
$channel->queue_bind(QUEUE_QC, NORMAL_EXCHANE, 'rk_qc');

// 延时交换机
$channel->exchange_declare(DELAY_EXCHANGE, 'direct');

$channel->queue_declare(DELAY_QUEUE);
$channel->queue_bind(DELAY_QUEUE, DELAY_EXCHANGE, 'rk_delay');

$channel->basic_consume(DELAY_QUEUE, '', false, true, false, false, function($msg) {
    echo "delay: " . $msg->body . PHP_EOL;
});

while ($channel->is_open()) {
    $channel->wait();
}

$channel->close();
$connection->close();